package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysWxUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysUserDept;
import com.ruoyi.system.mapper.SysUserDeptMapper;
import com.ruoyi.system.domain.SysUserComm;
import com.ruoyi.system.mapper.SysUserCommMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysWxUserMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.system.service.impl.SysWxUserServiceImpl;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class WxLoginService
{
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    // 登录类型，表示从哪里登录的，判断出从微信登录的用户
    private String loginType;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    // 定义token的前缀
    private static final String wx_prefix = "wx";

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysWxUserMapper wxUserMapper;

    @Autowired
    private SysUserDeptMapper userDeptMapper;

    @Autowired
    private SysUserCommMapper userCommMapper;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public WxUser getWxUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(wx_prefix);
            String userKey = getTokenKey(uuid);
            WxUser wxUser = redisCache.getCacheObject(userKey);
            return wxUser;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setWxUser(WxUser wxUser)
    {
        if (StringUtils.isNotNull(wxUser) && StringUtils.isNotEmpty(wxUser.getToken()))
        {
            refreshToken(wxUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delWxUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            // 解析token获取到存入redis中的key
            Claims claims = parseToken(token);
            String uuid = (String) claims.get(wx_prefix);

            String userKey = getTokenKey(uuid);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param wxUser 用户信息
     * @return 令牌
     */
    public String createToken(WxUser wxUser)
    {
        String token = IdUtils.fastUUID();
        wxUser.setToken(token);
        setUserAgent(wxUser);
        refreshToken(wxUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(wx_prefix, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param wxUser
     * @return 令牌
     */
    public void verifyToken(WxUser wxUser)
    {
        long expireTime = wxUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(wxUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param wxUser 登录信息
     */
    public void refreshToken(WxUser wxUser)
    {
        wxUser.setLoginTime(System.currentTimeMillis());
        wxUser.setExpireTime(wxUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将 wxUser 缓存
        String userKey = getTokenKey(wxUser.getToken());
        redisCache.setCacheObject(userKey, wxUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param wxUser 登录信息
     */
    public void setUserAgent(WxUser wxUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        wxUser.setIpaddr(ip);
        wxUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        wxUser.setBrowser(userAgent.getBrowser().getName());
        wxUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        System.out.println(token);
        if (StringUtils.isNotEmpty(token) && token.startsWith(wx_prefix))
        {
            token = token.replace(wx_prefix, "");
            // 从微信发过来的请求 返回jwt
            return token;
        } else {
            // 不是从微信发过来的请求返回 null 用于jwtFilter中的判断
            return null;
        }

    }

    private String getTokenKey(String uuid)
    {
        return "wx_token:" + uuid;
    }

    /**
     *
     * @param wxUser
     * @return
     */
    @Transactional
    public SysUser createUser(SysWxUser wxUser) {
        // 通过微信用户信息创建一个账号并绑定
        SysUser user = new SysUser();
        user.setUserName(IdUtils.fastSimpleUUID());
        user.setNickName(wxUser.getNickName());
        user.setAvatar(wxUser.getAvatar());
        user.setSex(wxUser.getSex());
        user.setRemark("根据微信信息自动生成");
        user.setCreateTime(new Date());
        user.setCommunityId(1);
        userMapper.insertUser(user);
        // 建立新用户和社区的关联，在 sys_user_dept 中插入数据
        // 将新用户与默认社区的 新注册用户关联 deptId = 245
        SysUserDept userDept = new SysUserDept(user.getUserId(), 245L, 1);
        userDeptMapper.insertSysUserDept(userDept);
        // 新用户绑定默认社区
        SysUserComm userComm = new SysUserComm(user.getUserId(), 1, "1");
        userCommMapper.insertSysUserComm(userComm);
        // 构造微信用户信息
        wxUser.setUserId(user.getUserId());
        wxUserMapper.insertSysWxUser(wxUser);
        return user;
    }
}
